/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pfc.arbol;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;
import pfc.comun.IDEpfc;
import pfc.comun.Proyecto;
import pfc.generacion.Application;
import pfc.generacion.GeneradorBO;
import pfc.generacion.GeneradorDTO;
import pfc.generacion.GeneradorDAO;
import pfc.generacion.GeneradorPKGenerator;
import pfc.generacion.GeneradorWEB;
import pfc.generacion.GeneradorValidacion;

/**
 *
 * @author xandru
 */
public class ApplicationTreeNode extends PFCTreeNode {

    private Application _app;

    public ApplicationTreeNode(Proyecto pro, Application p) {
        super(pro, p.getName());
        this._app = p;
        
    }

    protected void construirMenuContexto() {
        super.construirMenuContexto();
        JMenuItem mi = new JMenuItem("Borrar Aplicacion");
        this.popupMenu.add(mi);
        mi.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                deleteApp();
            }
        });


        JMenu menu = new JMenu("Generacion Codigo");
        this.popupMenu.add(menu);

        /*
        JMenuItem mi2 = new JMenuItem("Prueba");
        menu.add(mi2);
         */

        mi = new JMenuItem("Regenerar DTOs");
        menu.add(mi);
        mi.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                reGenerarFuentes("DTO");
            }
        });

        mi = new JMenuItem("Regenerar DAOs");
        menu.add(mi);
        mi.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                reGenerarFuentes("DAO");
            }
        });

        mi = new JMenuItem("Regenerar BOs");
        menu.add(mi);
        mi.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                reGenerarFuentes("BO");
            }
        });


        mi = new JMenuItem("Regenerar HTML");
        menu.add(mi);
        mi.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                reGenerarFuentes("HTML");
            }
        });



        mi = new JMenuItem("Clean & Build");
        this.popupMenu.add(mi);
        mi.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                cleanAndBuild();
            }
        });

        mi = new JMenuItem("Desplegar");
        this.popupMenu.add(mi);
        mi.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                deploy();
            }
        });

        mi = new JMenuItem("Generar todo & Desplegar");
        this.popupMenu.add(mi);
        mi.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                generarydeploy();
            }
        });

    }

    private void deleteApp() {
        IDEpfc.logTime("Eliminando aplicacion " + this.nombre);
        FolderTreeNode f = (FolderTreeNode) this.getParent();
        ProyectoTreeNode p = (ProyectoTreeNode) f.getParent();
        p._appManager.deleteApplication(this);

    }

    private void cleanAndBuild() {
        String buildFilePath = _app.getPath() + File.separator + "build.xml";
        System.out.println(buildFilePath);
        File buildFile = new File(buildFilePath);
        Project p = new Project();
        p.setUserProperty("ant.file", buildFile.getAbsolutePath());

        DefaultLogger consoleLogger = new DefaultLogger();
        //consoleLogger.setErrorPrintStream(System.err);
        //consoleLogger.setOutputPrintStream(System.out);
        OutputStream out = redirectSystemStreams();
        consoleLogger.setErrorPrintStream( new PrintStream(out) );
        consoleLogger.setOutputPrintStream( new PrintStream( out));
        consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
        p.addBuildListener(consoleLogger);



        try {
            p.fireBuildStarted();
            p.init();
            ProjectHelper helper = ProjectHelper.getProjectHelper();
            p.addReference("ant.projectHelper", helper);
            helper.parse(p, buildFile);
            p.executeTarget("build");
            p.fireBuildFinished(null);
        } catch (BuildException e) {
            p.fireBuildFinished(e);
        }

    }

    private void reGenerarFuentes(String string) {

        FolderTreeNode fn = (FolderTreeNode) this.getParent();
        ProyectoTreeNode n = (ProyectoTreeNode) fn.getParent();

        File srcPath = new File(this._app.getPath() + File.separator + this.proyecto.getSrcFolderName());

        if (StringUtils.equals(string, "DTO")) {
            GeneradorDTO genDTO = new GeneradorDTO(this.proyecto, n.getDatabase(), n.getERModel(), n.getCGModel());
            genDTO.generarDTOs(srcPath);
            return;
        }
        if (StringUtils.equals(string, "DAO")) {
            GeneradorDAO genDAO = new GeneradorDAO(this.proyecto, n.getDatabase(), n.getERModel(), n.getCGModel());
            genDAO.generarDAOs(srcPath);
            return;
        }

        if (StringUtils.equals(string, "BO")) {
            GeneradorBO genBO = new GeneradorBO(this.proyecto, n.getDatabase(), n.getERModel(), n.getCGModel());
            genBO.generarBOs(srcPath);
            return;
        }

        if (StringUtils.equals(string, "HTML")) {
            srcPath = new File(this._app.getPath().getPath());
            GeneradorWEB genWEB = new GeneradorWEB(this.proyecto, n.getDatabase(), n.getERModel(), n.getCGModel());
            genWEB.generarWEB(srcPath);
            return;
        }

        if (StringUtils.equals(string, "VAL")) {
            GeneradorValidacion genVal = new GeneradorValidacion(this.proyecto, n.getDatabase(), n.getERModel(), n.getCGModel());
            genVal.generar(srcPath);
            return;
        }

        if (StringUtils.equals(string, "PK")) {
            GeneradorPKGenerator gen = new GeneradorPKGenerator(this.proyecto, n.getDatabase(), n.getERModel(), n.getCGModel());
            gen.generar(srcPath);
            return;
        }




    }

    private void deploy() {
        String buildFilePath = _app.getPath() + File.separator + "build.xml";
        System.out.println(buildFilePath);
        File buildFile = new File(buildFilePath);
        Project p = new Project();
        p.setUserProperty("ant.file", buildFile.getAbsolutePath());

        DefaultLogger consoleLogger = new DefaultLogger();
        //consoleLogger.setErrorPrintStream(System.err);
        //consoleLogger.setOutputPrintStream(System.out);
        OutputStream out = redirectSystemStreams();
        consoleLogger.setErrorPrintStream( new PrintStream(out) );
        consoleLogger.setOutputPrintStream( new PrintStream( out));
        consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
        p.addBuildListener(consoleLogger);


        try {
            p.fireBuildStarted();
            p.init();
            ProjectHelper helper = ProjectHelper.getProjectHelper();
            p.addReference("ant.projectHelper", helper);
            helper.parse(p, buildFile);
            p.executeTarget("deploy");
            p.fireBuildFinished(null);
        } catch (BuildException e) {
            p.fireBuildFinished(e);
        }
    }

    private void generarydeploy() {
        reGenerarFuentes("DTO");
        reGenerarFuentes("DAO");
        reGenerarFuentes("PK");
        reGenerarFuentes("BO");
        reGenerarFuentes("VAL");
        reGenerarFuentes("HTML");
        deploy();
    }

    private OutputStream redirectSystemStreams() {
        OutputStream out = new OutputStream() {

            @Override
            public void write(int b) throws IOException {
                IDEpfc.updateTextArea(String.valueOf((char) b));
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                IDEpfc.updateTextArea(new String(b, off, len));
            }

            @Override
            public void write(byte[] b) throws IOException {
                write(b, 0, b.length);
            }
        };

        return out;

    }
}
